// comment.service.ts
import { CommentSingerDto, PagerDto } from '../../dto/singer/singer.dto';
import { CommentSinger } from '../../entities/comment.entity';
import { Singer } from '../../entities/singer.entity';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Like, Repository } from 'typeorm';

@Injectable()
export class CommentService {
  constructor(
    @InjectRepository(CommentSinger)
    private readonly commentRepository: Repository<CommentSinger>,
    @InjectRepository(Singer)
    private readonly singerRepository: Repository<Singer>,
  ) {}

  async findAll(): Promise<CommentSinger[]> {
    return await this.commentRepository.find({
      relations: ['singer'],
    });
  }

  async findById(dto: Partial<CommentSingerDto>): Promise<CommentSinger[]> {
    const { singerId, id, approved } = dto;

    const where: any = {};
    if (id) where.id = id;
    if (singerId) where.singer = Like(`%${singerId}%`);
    if (approved) where.approved = Like(`%${approved}%`);
    console.log(dto, where);

    return await this.commentRepository.find({
      where,
      relations: ['singer'],
    });
  }

  async create(
    commentData: Partial<CommentSinger & { singerId: string }>,
  ): Promise<CommentSinger> {
    // 从 commentData 中取出 singerId
    const { singerId, ...restData } = commentData;

    // 根据 singerId 查询对应的歌手
    const singer = await this.singerRepository.findOne({
      where: { id: singerId },
    });
    if (!singer) {
      throw new Error('找不到关联歌手');
    }

    // 将查询到的歌手关联到 commentData 中的 singer 属性
    restData.singer = singer;

    // 创建 CommentSinger 实例
    const comment = this.commentRepository.create(restData);

    // 保存 CommentSinger 实例到数据库
    return await this.commentRepository.save(comment);
  }
  async update(
    newData: Partial<CommentSinger & { singerId: string }>,
  ): Promise<CommentSinger> {
    // 从 newData 中提取 id 和 singerId
    const { id, singerId, ...restData } = newData;

    // 如果提供了 singerId，则根据 singerId 查询对应的歌手
    let singer;
    if (singerId) {
      singer = await this.singerRepository.findOne({ where: { id: singerId } });
      if (!singer) {
        throw new Error('找不到关联歌手');
      }
    }

    // 更新 CommentSinger 记录
    await this.commentRepository.update(id, {
      ...restData,
      singer: singer || undefined, // 如果提供了 singerId，则更新评论的歌手关联，否则不变
    });

    // 返回更新后的 CommentSinger 记录
    return await this.commentRepository.findOne({ where: { id } });
  }

  /**
   * 分页条件用户信息
   */
  async page(param: PagerDto): Promise<[Partial<CommentSinger>[], number]> {
    const { pageSize, pageNo, id, approved, content, singerId } = param;
    const where: any = {};
    if (id) where.id = id;
    if (approved) where.approved = Like(`%${approved}%`);
    if (content) where.content = Like(`%${content}%`);
    if (singerId) where.singer = Like(`%${singerId}%`);

    const [list, total] = await this.commentRepository.findAndCount({
      where,
      order: {
        createdTime: 'DESC',
      },
      relations: ['singer'],

      take: pageSize,
      skip: (pageNo - 1) * pageSize,
    });
    return [list, total];
  }

  async delete(id: string): Promise<void> {
    await this.commentRepository.delete(id);
  }

  async approve(dto: Partial<CommentSingerDto>): Promise<CommentSinger> {
    const comment = await this.commentRepository.findOne({
      where: { id: dto.id },
    });
    if (!comment) {
      throw new Error('CommentSinger not found');
    }
    comment.approved = dto.approved;
    return await this.commentRepository.save(comment);
  }
}
